import numpy as np
import pandas as pd
from common.config import opcUaConfig as Config
import os
from opcua import ua
'''
# 检查Explore 或 upload 文件是否存在，数据是否为空
'''

def getUploadCsv(uploadCsvFileName):
    if not os.path.exists(uploadCsvFileName):
        print(f"ERROR  {uploadCsvFileName} 文件不存在！")
        return pd.DataFrame()
    df = pd.read_csv(uploadCsvFileName)
    length = len(df)
    if length<=0:
        print(f"ERROR {uploadCsvFileName} 文件为空！")
        return pd.DataFrame()
    return df

'''
1.检查文件yawUpload.csv
2.上传yawUpload.csv
'''
def yawUpload(commonNodes):
    # 1.检查数据文件YawUpload.csv 是否存在，是否为空
    df = getUploadCsv(Config.YawUpload)
    if len(df) <= 0: return

    var = df.loc[0, Config.yawPlcKey ]
    if np.isnan(var): return
    var_set = ua.DataValue(ua.Variant(var, ua.VariantType.Float))

    commonNodes[Config.windDirOffsetNodeID_W].set_value(var_set)  # WindDirOffset 对应的PLC中节点id=10

'''
1.检查文件PitchUpload.csv
2.上传PitchUpload.csv
'''
def pitchUpload(commonNodes):
    # 1.检查数据文件YawUpload.csv 是否存在，是否为空
    df = getUploadCsv(Config.PitchUpload)

    if len(df) <= 0 :  return

    var = df.loc[0, Config.pitchPlcKey]
    if np.isnan(var): return
    var_set = ua.DataValue(ua.Variant(var, ua.VariantType.Float))

    commonNodes[Config.pitchOffsetNodeID_W].set_value(var_set)  # PitchOffset 对应的PLC中节点id=11

'''
1.检查文件TorqueUpload.csv
2.上传TorqueUpload.csv
'''
def torqueUpload(commonNodes):
    # 1.检查数据文件YawUpload.csv 是否存在，是否为空
    df = getUploadCsv(Config.TorqueUpload)
    if len(df) <= 0:  return

    var = df.loc[0, Config.torquePlcKey]
    if np.isnan(var): return
    var_set = ua.DataValue(ua.Variant(var, ua.VariantType.Float))

    # commonNodes[Config.kOptOffsetNodeID_W].set_value(var_set)  # KoptOffset 对应的PLC中节点id=12
    commonNodes[12].set_value(var_set)